package com.base.cn.platform.os.service.order.check;

import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.order.OrderSource;
import com.base.cn.platform.os.common.utils.order.OrderStatus;
import com.base.cn.platform.os.common.utils.order.PayType;
import com.base.cn.platform.os.common.utils.order.ShopType;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.entity.book.Book;
import com.base.cn.platform.os.entity.course.cou.Course;
import com.base.cn.platform.os.entity.course.cou.buy.CourseBuyRecord;
import com.base.cn.platform.os.entity.exam.paper.ExamPaper;
import com.base.cn.platform.os.entity.exam.record.ExamBuyRecord;
import com.base.cn.platform.os.entity.exam.record.ExamBuyRecordCondition;
import com.base.cn.platform.os.entity.order.order.OrderType;
import com.base.cn.platform.os.entity.order.shop.ShopData;
import com.base.cn.platform.os.entity.qa.question.QaQuestion;
import com.base.cn.platform.os.entity.user.member.CusUserMember;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品验证观察者对象
 *
 * @author s.li
 * @date 2019/05/27
 */
public class ShopCheckObserver extends OrderCheckObserver {
    /**
     * 初始化
     * @param createOrderDataFrom
     */
    public ShopCheckObserver(CreateOrderDataFrom createOrderDataFrom) {
        this.createOrderDataFrom = createOrderDataFrom;
        this.createOrderDataFrom.addObserver(this);
    }

    @Override
    public Map<String, Object> orderCheck() {
        List<ShopData> shopDataList = this.createOrderDataFrom.getShopList();
        if(!ObjectUtils.isNotEmpty(shopDataList)){
            return ResultUtil.ERROR("没有商品");
        }
        Map<String,List<ShopData>> shopMap = shopDataList.stream().collect(Collectors.groupingBy(e->e.getShopType()));
        if(createOrderDataFrom.getOrderType().equals(OrderType.COMMON.getKey())){
            if(shopMap.get(ShopType.ORDER_SHOP_ACCOUNT) !=null){
                return ResultUtil.ERROR("普通商品订单中不能包含账户充值商品");
            }
        }
        if(createOrderDataFrom.getOrderType().equals(OrderType.ACCOUNT.getKey())){
            List<ShopData> accountShopList = shopMap.get(ShopType.ORDER_SHOP_ACCOUNT);
            if(!ObjectUtils.isNotEmpty(accountShopList) || shopMap.size() > 1){
                return ResultUtil.ERROR("充值订单中，必须且只有包含有充值金额");
            }
        }
        if(createOrderDataFrom.isSubmit() && !createOrderDataFrom.isFree()){
            if((!OrderSource.ORDER_FORM_ANDROID.equals(createOrderDataFrom.getOrderForm())
                    && !OrderSource.ORDER_FORM_IOS.equals(createOrderDataFrom.getOrderForm())
                    && !OrderSource.ORDER_FORM_APPLY.equals(createOrderDataFrom.getOrderForm()))
                    && StringUtils.isEmpty(createOrderDataFrom.getPayType())){
                return ResultUtil.ERROR("请选择支付类型");
            }
        }
        if(createOrderDataFrom.isFree()){
            Map<String,List<ShopData>> shopListMap = createOrderDataFrom.getShopList().stream().collect(Collectors.groupingBy(e->e.getShopType()));
            shopListMap.remove(ShopType.ORDER_SHOP_COURSE);
            shopListMap.remove(ShopType.ORDER_SHOP_EXAM);
            //如果除去课程和试卷还有别的商品要免费生成订单，则报错
            if(ObjectUtils.isNotEmpty(shopListMap)){
                return ResultUtil.ERROR("商品数据错误，免费报名失败");
            }
        }
        //验证课程商品
        List<ShopData> courseShopList = shopMap.get(ShopType.ORDER_SHOP_COURSE);
        Map<String,Object> resultMap = this.checkCourse(courseShopList);
        if(!ResultUtil.getSuccess(resultMap)){
            return resultMap;
        }
        //验证试卷商品
        List<ShopData> examShopList = shopMap.get(ShopType.ORDER_SHOP_EXAM);
        resultMap = this.checkExam(examShopList);
        if(!ResultUtil.getSuccess(resultMap)){
            return resultMap;
        }
        //验证图书商品
        List<ShopData> bookShopList = shopMap.get(ShopType.ORDER_SHOP_BOOK);
        resultMap = this.checkBook(bookShopList);
        if(!ResultUtil.getSuccess(resultMap)){
            return resultMap;
        }
        //验证会员商品
        List<ShopData> memberShopList = shopMap.get(ShopType.ORDER_SHOP_MEMBER);
        resultMap = this.checkMember(memberShopList);
        if(!ResultUtil.getSuccess(resultMap)){
            return resultMap;
        }

        //验证旁听商品
        List<ShopData> attendQaShopList = shopMap.get(ShopType.ORDER_SHOP_ATTEND);
        resultMap = this.checkAttend(attendQaShopList);
        if(!ResultUtil.getSuccess(resultMap)){
            return resultMap;
        }
        //验证问答商品
        List<ShopData> qaShopList = shopMap.get(ShopType.ORDER_SHOP_QA);
        resultMap = this.checkQA(qaShopList);
        if(!ResultUtil.getSuccess(resultMap)){
            return resultMap;
        }
        //验证充值商品
        List<ShopData> accountShopList = shopMap.get(ShopType.ORDER_SHOP_ACCOUNT);
        resultMap = this.checkAccount(accountShopList);
        if(!ResultUtil.getSuccess(resultMap)){
            return resultMap;
        }
        return ResultUtil.SUCCESS();
    }

    /**
     * 验证课程商品数据的合法性
     * @param courseShopList 课程商品列表
     * @return Map<String,Object>
     */
    private Map<String,Object> checkCourse(List<ShopData> courseShopList){
        //课程商品不为空是，且不是系统自动赠送时，才需要验证
        if(ObjectUtils.isNotEmpty(courseShopList) && !createOrderDataFrom.isAutoGive()){
            for(ShopData shop : courseShopList){
                Course course = shop.getCourse();
                int status = course.getStatus();
                if(status!=1){
                    return ResultUtil.ERROR("课程【"+course.getCourseName()+"】已下架");
                }
                int validType = course.getValidType();
                if(validType==2){//时间段类型过期
                    Date validTime = course.getValidTime();
                    if(validTime.before(new Date())){
                        return ResultUtil.ERROR("课程【"+course.getCourseName()+"】有效期时间为【"+DateUtils.format(validTime,"yyyy-MM-dd HH:mm")+"】");
                    }
                    if(course.getDontBuyDate()<=0){
                        return ResultUtil.ERROR("课程【"+course.getCourseName()+"】已停止售卖");
                    }
                }
            }
            //查询用户购买记录
            String courseIds = courseShopList.stream().map(e->e.getShopId().toString()).distinct().collect(Collectors.joining(","));
            CourseBuyRecord courseBuyRecord = new CourseBuyRecord();
            courseBuyRecord.setUserId(createOrderDataFrom.getUserId());
            courseBuyRecord.setCourseIds(courseIds);
            courseBuyRecord.setCourseStatus(OrderStatus.SUCCESS);
            //验证是否重复购买
            Map<BigDecimal,List<CourseBuyRecord>> courseBuyRecordListMap = courseBuyRecordService.findCourseBuyRecordMap(courseBuyRecord,false);
            if(ObjectUtils.isNotEmpty(courseBuyRecordListMap)){
                for(ShopData shop : courseShopList){
                    List<CourseBuyRecord> _list = courseBuyRecordListMap.get(shop.getShopId());
                    if(ObjectUtils.isNotEmpty(_list)){
                        return ResultUtil.ERROR("【"+shop.getShopName()+"】课程已购买且未过期，不可重复购买");
                    }
                }
            }
        }
        return ResultUtil.SUCCESS();
    }

    /**
     * 验证试卷商品数据的合法性
     * @param examShopList 试卷商品列表
     * @return Map<String,Object>
     */
    private Map<String,Object> checkExam(List<ShopData> examShopList){
        if(ObjectUtils.isNotEmpty(examShopList)){
            for(ShopData shop : examShopList){
                ExamPaper exam = shop.getExam();
                int sale = exam.getSale();
                if(sale !=1 && (createOrderDataFrom.getPayType().equals(PayType.PAY_TYPE_ACCOUNT)
                        || createOrderDataFrom.getPayType().equals(PayType.PAY_TYPE_ALIPAY)
                        || createOrderDataFrom.getPayType().equals(PayType.PAY_TYPE_WEIXIN)
                        || createOrderDataFrom.getPayType().equals(PayType.PAY_TYPE_IOS))){
                    return ResultUtil.ERROR("试卷【"+exam.getName()+"】不是购买商品");
                }
                int status = exam.getStatus();
                if(status != 1){
                    return ResultUtil.ERROR("试卷【"+exam.getName()+"】已下架");
                }

            }
            //获取试卷购买记录接口
            ExamBuyRecordCondition condition = new ExamBuyRecordCondition();
            condition.setUserId(createOrderDataFrom.getUserId());
            condition.setExamIds(examShopList.stream().map(e->e.getShopId().toString()).collect(Collectors.joining(",")));
            Map<BigDecimal, ExamBuyRecord> examBuyRecordMap = examBuyRecordService.findExamBuyRecordMaps(condition);
            if(ObjectUtils.isNotEmpty(examBuyRecordMap)){
                for(ShopData shop : examShopList){
                    //购买记录
                    ExamBuyRecord examBuyRecord = examBuyRecordMap.get(shop.getShopId());
                    if(ObjectUtils.isNotEmpty(examBuyRecord)){
                        if(examBuyRecord.getAnswerNum() > 0 && examBuyRecord.getUseNum() >= examBuyRecord.getAnswerNum()){
                            return ResultUtil.ERROR("试卷【"+shop.getShopName()+"】已拥有使用权，不需要重新报名");
                        }
                    }
                }
            }
        }
        return ResultUtil.SUCCESS();
    }

    /**
     * 验证图书商品数据的合法性
     * @param bookShopList 图书商品列表
     * @return Map<String,Object>
     */
    private Map<String,Object> checkBook(List<ShopData> bookShopList){
        if(ObjectUtils.isNotEmpty(bookShopList)){
            for(ShopData shop : bookShopList){
                Book book = shop.getBook();
                int status = book.getStatus();
                if(status != 1){
                    return ResultUtil.ERROR("图书【"+book.getBookName()+"】已下架");
                }
                //库存量
                int stockNum =book.getStockNum();
                if(stockNum <= 0 || shop.getBuyNum()> stockNum){
                    return ResultUtil.ERROR("图书【"+book.getBookName()+"】,当前库存【"+stockNum+"本】，库存不足");
                }
            }
            //是提交订单，且不是重新验证时才需要验证收货地址
            if(createOrderDataFrom.isSubmit() && !createOrderDataFrom.isCheckAgain()){
                if((!DataUtil.idIsNotNull(createOrderDataFrom.getAddressId()) || StringUtils.isEmpty(createOrderDataFrom.getAddress()))){
                    return ResultUtil.ERROR("订单中包含有图书实物商品，请选择收货地址");
                }
            }
        }
        return ResultUtil.SUCCESS();
    }

    /**
     * 验证试卷商品数据的合法性
     * @param memberShopList 会员商品列表
     * @return Map<String,Object>
     */
    private Map<String,Object> checkMember(List<ShopData> memberShopList){
        if(ObjectUtils.isNotEmpty(memberShopList)){
            for(ShopData shop : memberShopList){
                //获取会员对象
                CusUserMember member = shop.getMember();
                //会员状态
                int status = member.getStatus();
                if(status != 1){
                    return ResultUtil.ERROR("会员【"+member.getMemberName()+"】已下架");
                }
                //会员类型
                int memberType = member.getMemberType ();
                if(memberType!=1){
                    return ResultUtil.ERROR("会员【"+member.getMemberName()+"】不可购买");
                }
            }
        }
        return ResultUtil.SUCCESS();
    }

    /**
     * 验证试卷商品数据的合法性
     * @param qaShopList 问答商品列表
     * @return Map<String,Object>
     */
    private Map<String,Object> checkAttend(List<ShopData> qaShopList){
        if(ObjectUtils.isNotEmpty(qaShopList)){
            for(ShopData shopData : qaShopList){
                QaQuestion question = shopData.getQa();
                if(question.getStatus() != 1){
                    return ResultUtil.ERROR("问答【"+question.getContext()+"】状态异常，不可旁听");
                }
                if(question.getIsFree() !=2){
                    return ResultUtil.ERROR("问答【"+question.getContext()+"】不是付费问答，不可旁听");
                }
                //检查用户是否围观过这个问题
                 HashMap   attend =  new HashMap<>();
                attend.put("questionId",question.getId());
                attend.put("userId",  createOrderDataFrom.getUserId());
                List qaAttendList = qaAttendService.findQaAttendList(attend, false);
                if(!qaAttendList.isEmpty()){
                    return ResultUtil.ERROR("已经围观过了");
                }
            }
        }
        return ResultUtil.SUCCESS();
    }

    /**
     * 验证试卷商品数据的合法性
     * @param qaShopList 问答商品列表
     * @return Map<String,Object>
     */
    private Map<String,Object> checkQA(List<ShopData> qaShopList){
        if(ObjectUtils.isNotEmpty(qaShopList)){
            for(ShopData shopData : qaShopList){
                QaQuestion question = shopData.getQa();
                if(question.getStatus() != 0){
                    if(question.getStatus()==1){
                        return ResultUtil.ERROR("问答【"+question.getContext()+"】已支付成功，不可重复支付");
                    }else{
                        return ResultUtil.ERROR("问答【"+question.getContext()+"】状态异常，不可支付");
                    }
                }
                if(question.getIsFree() !=2){
                    return ResultUtil.ERROR("问答【"+question.getContext()+"】不是付费问答，不可支付");
                }
            }
        }
        return ResultUtil.SUCCESS();
    }

    /**
     * 验证充值商品数据的合法性
     * @param accountShopList 充值商品列表
     * @return Map<String,Object>
     */
    private Map<String,Object> checkAccount(List<ShopData> accountShopList){
        if(ObjectUtils.isNotEmpty(accountShopList)){
            for (ShopData shopData : accountShopList){
                double realPrice = shopData.getRealPrice();
                if(realPrice <=0 || realPrice > 9999){
                    return ResultUtil.ERROR("账户充值金额必须大于0，且不能超￥9999");
                }
            }
        }
        return ResultUtil.SUCCESS();
    }
}
